import cookie from 'cookie';

const getAllCookies = () => {
    const cookies = cookie.parse(document.cookie)
    return cookies
}

const getCookie = (name: string) => {
    const cookies = cookie.parse(document.cookie)
    const value = cookies && cookies[name]
    if (value) {
        const hasToParse = Boolean((value && value[0] === '{') || value[0] === '[')
        return hasToParse ? JSON.parse(value) : value
    }
    return null
}

const removeCookie = (name: string) => {
    const options = { expires: new Date(1970, 1, 1, 0, 0, 1), maxAge: 0 }

    document.cookie = cookie.serialize(name, '', options)

    return document.cookie
}

type CookieOptions = {
    expire?: number | Date
    maxAge?: number
    domain?: string
    path?: string
    secure?: boolean
    httpOnly?: boolean
}

const setCookie = (name: string, value: unknown, options: CookieOptions = {}) => {
    const rawCookie: any = {}
    rawCookie[name] = value

    if (typeof value === 'object') {
        rawCookie[name] = JSON.stringify(value)
    }

    document.cookie = cookie.serialize(name, rawCookie[name], options)

    return document.cookie
}

export default {
    getAllCookies,
    getCookie,
    removeCookie,
    setCookie
}